<script setup>
	import { nextTick, ref } from 'vue'
	import ApiSimpleQuery from './ApiSimpleQuery.vue'
	import { useApiDatasetStore } from '@/views/plugin/dashboard/store/apiDataset'
	import { message } from 'ant-design-vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'

	const apiDatasetStore = useApiDatasetStore()
	const apiSimpleQueryRef = ref()
	const currentType = ref('query')
	const formData = ref({})
	const emit = defineEmits(['loadData'])

	// 打开抽屉
	const onOpen = (record) => {
		if (record) {
			// 支持API指标类型
			currentType.value = record.type === 'api_query' ? 'query' : (record.type || 'query')
			nextTick(() => {
				if (currentType.value === 'query') {
					formData.value = {
						...{
							id: '',
							dataConnectorId: '',
							type: record.type || 'query',
							itemConfig: {
								// API接口路径
								apiPath: '',
								// API请求方法（固定为GET）
								apiMethod: 'GET',
								// API请求参数
								apiParams: {},
								// 驼峰转换状态
								enableCamelCase: false,
								// 选中的列
								selectedColumns: [],
								// 格式化配置
								formatConfig: [],
								// 表格列定义
								columns: []
							}
						},
						...record
					}
					apiSimpleQueryRef.value?.onOpen(formData.value)
				} else {
					// API连接器暂不支持自定义查询
					message.warning('API连接器暂不支持自定义查询')
				}
			})
		}
	}

	// 获取配置
	const getConfig = async () => {
		if (currentType.value === 'query') {
			return await apiSimpleQueryRef.value?.getConfig()
		}
		return null
	}

	// 关闭方法
	const onClose = () => {
		// 清空数据
		formData.value = {}
	}

	// 保存数据集配置
	const onSave = async () => {
		try {
			// 获取API数据集配置
			const config = apiDatasetStore.formData
			if (!config) {
				message.error('请完善API数据集配置')
				return
			}

			const itemConfig = config.itemConfig
			if (!itemConfig.apiPath) {
				message.error('请选择API接口')
				return
			}

			if (!itemConfig.selectedColumns || itemConfig.selectedColumns.length === 0) {
				message.error('请选择数据字段')
				return
			}

			const params = {
				id: formData.value.id,
				datasetId: config.datasetId,
				itemConfig: itemConfig,
				type: formData.value.type || currentType.value
			}
			await datasetApi.saveItemConfig(params)
			emit('loadData')
			onClose()
		} catch (error) {
			console.log(error)
		}
	}

	defineExpose({
		onOpen,
		getConfig,
		currentType
	})
</script>

<template>
	<div class="api-dataset-container">
		<api-simple-query
			v-if="currentType === 'query'"
			ref="apiSimpleQueryRef"
			@loadData="emit('loadData')"
			@onSave="onSave"
		/>
		<div v-else class="empty-container">
			<a-empty description="API连接器暂不支持自定义查询" />
		</div>
	</div>
</template>

<style scoped>
	.api-dataset-container {
		width: 100%;
		height: 100%;
		background: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.empty-container {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 400px;
		color: #8c8c8c;
	}
</style>
